import {Component} from '@angular/core';
import {AlertController, IonicPage, NavController, NavParams} from 'ionic-angular';
import {FormBuilder, FormGroup, Validators} from "@angular/forms";
import {Setting} from "../../public/setting/setting";
import {Util} from "../../public/service/util";
import {UserService} from "../../services/user.service";

@IonicPage()
@Component({
  selector: 'page-reactive',
  templateUrl: 'reactive.html',
})
export class ReactivePage {
  public validateForm: FormGroup = this.fb.group({
    payType: [null, [Validators.required]]
  });//登录的表单
  payTypes: Array<{ key, val }> = [];
  public isRefresh: boolean = true;

  constructor(private fb: FormBuilder, public navCtrl: NavController, private util: Util,
              private userService: UserService, public navParams: NavParams, private alertCtrl: AlertController) {
  }

  ionViewDidLoad() {
    this.payTypes = this.util.getEnumDataList(Setting.ENUM.payTypes);
  }

  recast($event) {
    $event.preventDefault();
    let me = this;
    for (const key in me.validateForm.controls) {
      me.validateForm.controls[key].markAsDirty();
      me.validateForm.controls[key].updateValueAndValidity();
    }
    if (me.validateForm.invalid) return;
    this.passwordPrompt();
  };

  getFormControl(name) {
    return this.validateForm.controls[name];
  }

  passwordPrompt() {
    this.isRefresh = false;
    let alert = this.alertCtrl.create({
      title: '交易密码',
      inputs: [
        {
          name: 'password',
          type: 'password',
          placeholder: '请输入交易密码'
        }
      ],
      buttons: [
        {
          text: '确认',
          handler: data => {
            if (!data.password || data.password === '') return false;
            else {
              this.userService.recast({
                payType: this.validateForm.value.payType,
                pinPassword: data.password
              }).then(res => {
                this.isRefresh = true;
              }).catch(err => {
                return false
              })
            }
          }
        }
      ]
    });
    alert.present();
  }

}
